package ch.connection;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import javax.net.ServerSocketFactory;

/** Classe per la gestione del server SMTP
 * 
 * @author Giovanni Franza - GPLv3 - 8/6/2011
 *
 */

public class SMTP extends Thread {

	private StateManager sm;
	private User user = new User();

	/** Construttore - setta la macchina a stati.
	 *
	 */
	
	public SMTP() {		
		sm = new StateManager( "220 Welcome to javasmtpserver\n", "250 2.0.0 Ok: queued\n", ':' );
		sm.add( new Action( StateManager.SAME, "helo", null,  "250 Server online\n", "504 5.5.2: va da via i pe\n", StateManager.CHANGE ) );
		sm.add( new Action( StateManager.SAME, "Quit", null,  "221 2.0.0 Bye\n", "504 5.5.2: va da via i pe\n", StateManager.ABORT ) );
		sm.add( new Action( StateManager.CHANGE, "Mail From", null,  "250 2.1.0 Ok\n", "504 5.5.2: va da via i pe\n", StateManager.CHANGE ) );
		sm.add( new Action( StateManager.SAME, "Quit", null,  "221 2.0.0 Bye\n", "504 5.5.2: va da via i pe\n", StateManager.ABORT ) );
		sm.add( new Action( StateManager.CHANGE, "RCPT To", user,  "250 2.1.5 Ok\n", "504 5.5.2: va da via i pe\n", StateManager.CHANGE ) );
		sm.add( new Action( StateManager.SAME, "Quit", null,  "221 2.0.0 Bye\n", "504 5.5.2: va da via i pe\n", StateManager.ABORT ) );
		sm.add( new Action( StateManager.CHANGE, "Data", null,  "354 End data with <CR><LF>.<CR><LF>\n", "504 5.5.2: va da via i pe\n", StateManager.CHANGE ) );
		sm.add( new Action( StateManager.SAME, "Quit", null,  "221 2.0.0 Bye\n", "221 2.0.0 Bye\n", StateManager.ABORT ) );
		sm.add( new Action( StateManager.CHANGE, "Quit", null,  "221 2.0.0 Bye\n", "500\n", StateManager.ABORT ) );
	}
	
	/** getter della macchina a stati.
	 *
	 */

	public StateManager getStateManager( ) {
		return sm;
	}

	/** Il run fa tutto il lavoro.
	 *
	 */	

	public void run() {
		try {
			System.out.println( "Welcome to the stupid, quick and dirty SMTP server" ); 
			System.out.println( "Licenced as per GPLv3 by HB9EIK - Giovanni" ); 
			// unprivileged port to be able to launch as not root
		    int port = 1025;
		    // SMTP server creation
		    ServerSocketFactory socketFactory = ServerSocketFactory.getDefault();
			ServerSocket ssocket = socketFactory.createServerSocket(port);
			// Serving requests (serialized) 
			for( ;; ) {
			    // Listen for connections
			    Socket socket = ssocket.accept();	
			    // Handle connections
			    SMTPWorker sslworker = new SMTPWorker( socket, this );
			    sslworker.start();
			}
		} catch(IOException e) {
			System.out.println(e);
		}
	}

}
